import api from './api.js'
import { dateFormat } from './utils.js'

function render($el, data) {
  let html = ''
  for(let i = 0; i < data.length; i++) {
    const item = data[i]
    html += `
      <a class="list-group-item list-group-item-action flex-column align-items-start">
        <div class="d-flex w-100 justify-content-between">
          <h5 class="mb-1">${item.title}</h5>
          <small>
            <button type="button" class="btn btn-secondary" value="${item.id}">Edit</button>
            <button type="button" class="btn btn-danger" value="${item.id}">Delete</button>
          </small>
        </div>
        <small>${dateFormat(item.createtime)}</small>
        <small>${item.author}</small>
      </a>
    `
  }
  $el.innerHTML = html

  // bin edit click event
  $('#list .btn.btn-secondary').click((e) => {
    e.preventDefault()
    const id = e.target.value
    window.location.href = '/edit.html?id=' + id
  })
  // bin delete click event
  $('#list .btn.btn-danger').click((e) => {
    e.preventDefault()
    const id = e.target.value
    let result = api.deleteArticle(id)
    result.then(res => {
      if (res.errno === 0) {
        console.log(res)
        $('.alert.alert-success').show()
        setTimeout(() => {
          $('.alert.alert-success').hide()
          window.location.reload()
        }, 2000);
      } else {
        $('.alert.alert-danger').show()
        console.log('res.errno:', res.errno)
      }
    }).catch(err => {
      console.error(err)
    })
  })
}

let articleList = api.getListAdmin()
articleList.then(res => {
  if (res.errno === 0) {
    let data = res.data
    render($('#list')[0], data)
    console.log(data)
  } else {
    console.log(res)
  }
}).catch(err => {
  console.error(err)
})
